package com.fg.cloud.factory.controller.agency;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.fg.cloud.common.PageUtils;
import com.fg.cloud.common.StatusCode;
import com.fg.cloud.common.finals.Agency;
import com.fg.cloud.common.quantity.ResultType;
import com.fg.cloud.common.validate.LongUtils;
import com.fg.cloud.framework.controller.BaseController;
import com.fg.cloud.manager.entry.agency.AgencyProductEntity;
import com.fg.cloud.manager.entry.agency.vo.AgencyProductVo;
import com.fg.cloud.manager.entry.factory.vo.FactoryUserVo;
import com.fg.cloud.manager.service.agency.AgencyPriceService;

/**
 * Description:经销商特价管理Controller
 * @author around
 * @date 2017年8月3日上午11:38:18
 */
@Controller
@RequestMapping("/agencyPrice")
public class AgencyPriceController extends BaseController {

	@Autowired
	private AgencyPriceService agencyPriceService;
	
	/**
	 * Description:经销商价格政策列表数据查询
	 * @param request
	 * @param response
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param filter
	 * @param categoryId
	 * @param ageId
	 * @author around
	 * @date 2017年8月4日下午5:40:35
	 */
	@RequestMapping(value = "/findList", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void findList(HttpServletRequest request, HttpServletResponse response, 
			Integer page, Integer rows, String sort, String order,
			String filter, Long categoryId, Long ageId) {
		try {
			FactoryUserVo user = getCurrentFactoryUser();
			PageUtils<AgencyProductVo> pageinfo = 
					new PageUtils<>(page, rows, replaceSort(sort), order);
			Map<String, Object> condition = pageinfo.getCondition();
			condition.put("filter", filter);
			condition.put("ageId", ageId);
			condition.put("categoryId", categoryId);
			condition.put("facId", user.getFacId());
			pageinfo.setTablename(Agency.getTableName(user.getFacId()));
			
			agencyPriceService.findList(pageinfo);
			doResult(response,true,StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (org.springframework.jdbc.BadSqlGrammarException e) {
			doResult(response,false,StatusCode.FINDERROR, null, "查询条件异常");
			e.printStackTrace();
		} catch (Exception e) {
			doResult(response,false,StatusCode.FINDERROR, null, ResultType.FIND_FAULT);
			e.printStackTrace();
		}
	}
	
	/**
	 * Description:批量删除
	 * @param response
	 * @param ageId 经销商ID
	 * @param ids 待删除ID集合
	 * @author around
	 * @date 2017年8月4日下午3:04:58
	 */
	@RequestMapping(value = "/deletes", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void deletes(HttpServletResponse response, Long ageId, String ids) {
		if(ageId == null) {
			doResult(response,false,StatusCode.REMOVEERROR, null, "缺少经销商ID");
			return;
		}
		if(ids == null || ids.length() == 0) {
			doResult(response,false,StatusCode.REMOVEERROR, null, "请选择必要参数");
			return;
		}
		try {
			boolean flag = agencyPriceService.deletes(getCurrentFactoryUser().getFacId(), ageId, 
					LongUtils.convert(ids.split("[, ]+")));
			doResult(response, flag, flag ? StatusCode.REMOVESUCCESS:StatusCode.REMOVEERROR, 
					null, flag ? ResultType.REMOVE_SUCCESS:ResultType.REMOVE_FAULT);
		} catch (Exception e) {
			doResult(response,false,StatusCode.REMOVEERROR, null, ResultType.REMOVE_FAULT);
			e.printStackTrace();
		}
	}
	
	/**
	 * Description:查询经销商价格政策待新增数据
	 * @param response
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param ageId
	 * @param filter
	 * @param categoryId
	 * @author around
	 * @date 2017年8月4日下午5:39:59
	 */
	@RequestMapping(value = "/select", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void select(HttpServletResponse response, Integer page, Integer rows, 
			String sort, String order,Long ageId, String filter, Long categoryId) {
		try {
			FactoryUserVo user = getCurrentFactoryUser();
			PageUtils<AgencyProductVo> pageinfo = 
					new PageUtils<>(page, rows, replaceSort(sort), order);
			Map<String, Object> condition = pageinfo.getCondition();
			condition.put("filter", filter);
			condition.put("ageId", ageId);
			condition.put("categoryId", categoryId);
			condition.put("facId", user.getFacId());
			pageinfo.setTablename(Agency.getTableName(user.getFacId()));
			
			agencyPriceService.select(pageinfo);
			doResult(response,true,StatusCode.FINDSUCCESS, pageinfo, ResultType.FIND_SUCCESS);
		} catch (org.springframework.jdbc.BadSqlGrammarException e) {
			doResult(response,false,StatusCode.FINDERROR, null, "查询条件异常");
			e.printStackTrace();
		} catch (Exception e) {
			doResult(response,false,StatusCode.FINDERROR, null, ResultType.FIND_FAULT);
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "/insert", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void insert(HttpServletRequest request, HttpServletResponse response, 
			String objText) {
		//[{"facId":0,"ageId":0,"proId":7,"price":17.2}]
		try {
			List<AgencyProductEntity> list = JSON.parseArray(
					StringEscapeUtils.unescapeHtml4(objText), AgencyProductEntity.class);
			
			if (null == list || 0 == list.size()) {
				doResult(response,false,StatusCode.SAVEERROR, null, "请勾选数据");
				return;
			}
			
			boolean flag = agencyPriceService.insert(getCurrentFactoryUser().getFacId(), list);
			doResult(response,flag,flag ? StatusCode.SAVESUCCESS : StatusCode.SAVEERROR, 
					null, flag ? ResultType.SAVE_SUCCESS : ResultType.SAVE_FAULT);
		} catch (com.alibaba.fastjson.JSONException e) {
			doResult(response,false,StatusCode.SAVEERROR, null, "参数填写格式错误");
			e.printStackTrace();
		} catch (Exception e) {
			doResult(response,false,StatusCode.SAVEERROR, null, ResultType.SAVE_FAULT);
			e.printStackTrace();
		}
	}
	
	
	@RequestMapping(value = "/update", method = {RequestMethod.POST, RequestMethod.GET})
	@ResponseBody
	public void update(HttpServletResponse response, AgencyProductEntity product) {
		if(null == product.getId()) {
			doResult(response,false,StatusCode.SAVEERROR, null, "缺少ID");
			return;
		}
		if(null == product.getPrice()) {
			doResult(response,false,StatusCode.SAVEERROR, null, "缺少金额项");
			return;
		}
		try {
			product.setFacId(getCurrentFactoryUser().getFacId());
			boolean flag = agencyPriceService.update(product);
			doResult(response, flag, flag ? StatusCode.SAVESUCCESS:StatusCode.SAVEERROR, 
					null, flag ? ResultType.SAVE_SUCCESS:ResultType.SAVE_FAULT);
		} catch (Exception e) {
			doResult(response,false,StatusCode.SAVESUCCESS, null, ResultType.SAVE_FAULT);
			e.printStackTrace();
		}
	}
	
	
	/**
	 * Description:处理排序字段的别名拼接问题
	 * @param sort
	 * @return String
	 * @author around
	 * @date 2017年8月4日上午11:38:34
	 */
	private String replaceSort(String sort) {
		if ("productName,productNumber".indexOf(sort) != -1)
			return "ps."+sort;
		else if ("categoryName".indexOf(sort) != -1)
			return "pc."+sort;
		else if ("unitName".indexOf(sort) != -1)
			return "pu."+sort;
		else {
			return "ap.id";
		}
	}
	
}
